package test.designmode.masterworker;

import java.util.Queue;

/**
 * @param <T> 任务(参数)
 */
public abstract class Worker<T extends Object> implements Runnable {
    /* 这2参数都是引用Master里面的, 相当一个代理 */
    private Queue<Object> jobQueue;
    private Queue<Object> resultQueue;

    public Queue<Object> getJobQueue() {
        return jobQueue;
    }

    public void setJobQueue(Queue<Object> jobQueue) {
        this.jobQueue = jobQueue;
    }

    public Queue<Object> getResultQueue() {
        return resultQueue;
    }

    public void setResultQueue(Queue<Object> resultQueue) {
        this.resultQueue = resultQueue;
    }

    @Override
    public void run() {
        while (true) {
            /* 有任务就执行,没任务了就直接结束线程 */
            Object job = jobQueue.poll();
            if (job == null) {
                break;
            }
            Object result = handle((T) job);
            resultQueue.add(result);
        }
    }

    /**
     * 处理任务的核心
     *
     * @param arg
     * @return 任务处理的结果
     */
    public abstract Object handle(T arg);
}
